/*
 * @Descripttion: 第三方格式库
 * @Version: 1.0
 * @Author: undead
 * @Date: 2022-01-12 15:31:32
 * @LastEditors: undead
 * @LastEditTime: 2022-01-12 16:01:07
 */
var request = require("request");

var headers = {
  authority: "closure-compiler.appspot.com",
  pragma: "no-cache",
  "cache-control": "no-cache",
  "sec-ch-ua":
    '" Not A;Brand";v="99", "Chromium";v="96", "Microsoft Edge";v="96"',
  dnt: "1",
  "sec-ch-ua-mobile": "?0",
  "user-agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62",
  "sec-ch-ua-platform": '"Windows"',
  "content-type": "application/x-www-form-urlencoded;charset=UTF-8",
  accept: "*/*",
  origin: "https://closure-compiler.appspot.com",
  "sec-fetch-site": "same-origin",
  "sec-fetch-mode": "cors",
  "sec-fetch-dest": "empty",
  referer: "https://closure-compiler.appspot.com/home",
  "accept-language": "zh,zh-CN;q=0.9,en;q=0.8",
};

var objectToString = function (obj) {
  return Object.keys(obj)
    .map((x) => `${x}=${obj[x]}`)
    .join("&");
};

var options = {
  url: "https://closure-compiler.appspot.com/compile",
  method: "POST",
  headers: headers
};

async function main(js_code) {
  options.body = objectToString({
    output_format: "json",
    output_info: "statistics",
    compilation_level: "ADVANCED_OPTIMIZATIONS",
    warning_level: "verbose",
    output_file_name: "default.js",
    js_code: js_code,
  });
  return new Promise((resolve, reject) => {
    request(options, (error, response, body) => {
      if (!error && response.statusCode == 200) {
        console.log(body);
        resolve(body);
      } else if (error) {
        console.log(error);
        reject(error);
      }
    });
  });
}
module.exports = main;
